import java.sql.*;
import java.util.*;

public class Test {
    private static Scanner scanner = new Scanner(System.in);
    private static User currentUser = null;

    public static void main(String[] args) {
        System.out.println("欢迎使用网上订餐系统!");

        while (true) {
            if (currentUser == null) {
                showMainMenu();
            } else {
                showUserMenu();
            }
        }
    }

    private static void showMainMenu() {
        System.out.println("\n===== 主菜单 =====");
        System.out.println("1. 用户注册");
        System.out.println("2. 用户登录");
        System.out.println("3. 浏览餐厅");
        System.out.println("4. 退出系统");
        System.out.print("请选择操作: ");

        int choice = scanner.nextInt();
        scanner.nextLine(); // 清除缓冲区

        switch (choice) {
            case 1:
                registerUser();
                break;
            case 2:
                loginUser();
                break;
            case 3:
                browseRestaurants();
                break;
            case 4:
                System.out.println("感谢使用，再见!");
                System.exit(0);
                break;
            default:
                System.out.println("无效选择，请重新输入!");
        }
    }

    private static void showUserMenu() {
        System.out.println("\n===== 用户菜单 (" + currentUser.getUsername() + ") =====");
        System.out.println("1. 浏览餐厅");
        System.out.println("2. 查看菜单");
        System.out.println("3. 下单");
        System.out.println("4. 查看我的订单");
        System.out.println("5. 修改个人信息");
        System.out.println("6. 退出登录");
        System.out.print("请选择操作: ");

        int choice = scanner.nextInt();
        scanner.nextLine(); // 清除缓冲区

        switch (choice) {
            case 1:
                browseRestaurants();
                break;
            case 2:
                viewMenu();
                break;
            case 3:
                placeOrder();
                break;
            case 4:
                viewMyOrders();
                break;
            case 5:
                updateUserInfo();
                break;
            case 6:
                currentUser = null;
                System.out.println("已退出登录!");
                break;
            default:
                System.out.println("无效选择，请重新输入!");
        }
    }

    private static void registerUser() {
        System.out.println("\n===== 用户注册 =====");
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine();
        System.out.print("请输入邮箱: ");
        String email = scanner.nextLine();
        System.out.print("请输入电话: ");
        String phone = scanner.nextLine();
        System.out.print("请输入地址: ");
        String address = scanner.nextLine();

        try (Connection conn = DatabaseConnection.getConnection()) {
            String sql = "INSERT INTO users (username, password, email, phone, address) VALUES (?, ?, ?, ?, ?)";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            pstmt.setString(3, email);
            pstmt.setString(4, phone);
            pstmt.setString(5, address);

            int rowsAffected = pstmt.executeUpdate();
            if (rowsAffected > 0) {
                System.out.println("注册成功!");
            } else {
                System.out.println("注册失败!");
            }
        } catch (SQLException e) {
            if (e.getErrorCode() == 1062) { // 重复用户名
                System.out.println("用户名已存在，请选择其他用户名!");
            } else {
                e.printStackTrace();
            }
        }
    }

    private static void loginUser() {
        System.out.println("\n===== 用户登录 =====");
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine();

        try (Connection conn = DatabaseConnection.getConnection()) {
            String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            pstmt.setString(2, password);

            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                currentUser = new User();
                currentUser.setId(rs.getInt("id"));
                currentUser.setUsername(rs.getString("username"));
                currentUser.setPassword(rs.getString("password"));
                currentUser.setEmail(rs.getString("email"));
                currentUser.setPhone(rs.getString("phone"));
                currentUser.setAddress(rs.getString("address"));
                System.out.println("登录成功! 欢迎 " + username + "!");
            } else {
                System.out.println("用户名或密码错误!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static void browseRestaurants() {
        System.out.println("\n===== 餐厅列表 =====");

        try (Connection conn = DatabaseConnection.getConnection()) {
            String sql = "SELECT * FROM restaurants";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);

            while (rs.next()) {
                Restaurant restaurant = new Restaurant();
                restaurant.setId(rs.getInt("id"));
                restaurant.setName(rs.getString("name"));
                restaurant.setDescription(rs.getString("description"));
                restaurant.setAddress(rs.getString("address"));
                restaurant.setPhone(rs.getString("phone"));
                restaurant.setRating(rs.getDouble("rating"));

                System.out.println(restaurant.getId() + ". " + restaurant.getName() +
                        " - 评分: " + restaurant.getRating());
                System.out.println("   描述: " + restaurant.getDescription());
                System.out.println("   地址: " + restaurant.getAddress());
                System.out.println("   电话: " + restaurant.getPhone());
                System.out.println();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static void viewMenu() {
        System.out.print("请输入餐厅ID: ");
        int restaurantId = scanner.nextInt();
        scanner.nextLine(); // 清除缓冲区

        System.out.println("\n===== 菜单 =====");

        try (Connection conn = DatabaseConnection.getConnection()) {
            String sql = "SELECT * FROM menu_items WHERE restaurant_id = ?";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, restaurantId);
            ResultSet rs = pstmt.executeQuery();

            while (rs.next()) {
                MenuItem item = new MenuItem();
                item.setId(rs.getInt("id"));
                item.setRestaurantId(rs.getInt("restaurant_id"));
                item.setName(rs.getString("name"));
                item.setDescription(rs.getString("description"));
                item.setPrice(rs.getDouble("price"));
                item.setCategory(rs.getString("category"));

                System.out.println(item.getId() + ". " + item.getName() +
                        " - ￥" + item.getPrice());
                System.out.println("   描述: " + item.getDescription());
                System.out.println("   分类: " + item.getCategory());
                System.out.println();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static void placeOrder() {
        if (currentUser == null) {
            System.out.println("请先登录!");
            return;
        }

        System.out.print("请输入餐厅ID: ");
        int restaurantId = scanner.nextInt();
        scanner.nextLine(); // 清除缓冲区

        List<OrderItem> orderItems = new ArrayList<>();
        double totalAmount = 0;

        while (true) {
            System.out.print("请输入菜品ID (输入0结束): ");
            int menuItemId = scanner.nextInt();
            scanner.nextLine(); // 清除缓冲区

            if (menuItemId == 0) {
                break;
            }

            System.out.print("请输入数量: ");
            int quantity = scanner.nextInt();
            scanner.nextLine(); // 清除缓冲区

            // 获取菜品价格
            try (Connection conn = DatabaseConnection.getConnection()) {
                String sql = "SELECT price FROM menu_items WHERE id = ? AND restaurant_id = ?";
                PreparedStatement pstmt = conn.prepareStatement(sql);
                pstmt.setInt(1, menuItemId);
                pstmt.setInt(2, restaurantId);
                ResultSet rs = pstmt.executeQuery();

                if (rs.next()) {
                    double price = rs.getDouble("price");
                    orderItems.add(new OrderItem(0, menuItemId, quantity, price));
                    totalAmount += price * quantity;
                    System.out.println("已添加: " + quantity + " 份，当前总计: ￥" + totalAmount);
                } else {
                    System.out.println("菜品ID不存在或不属于该餐厅!");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (orderItems.isEmpty()) {
            System.out.println("订单为空，取消下单!");
            return;
        }

        System.out.print("请输入配送地址: ");
        String deliveryAddress = scanner.nextLine();

        // 创建订单
        try (Connection conn = DatabaseConnection.getConnection()) {
            conn.setAutoCommit(false); // 开始事务

            // 插入订单
            String orderSql = "INSERT INTO orders (user_id, restaurant_id, total_amount, delivery_address) VALUES (?, ?, ?, ?)";
            PreparedStatement orderStmt = conn.prepareStatement(orderSql, Statement.RETURN_GENERATED_KEYS);
            orderStmt.setInt(1, currentUser.getId());
            orderStmt.setInt(2, restaurantId);
            orderStmt.setDouble(3, totalAmount);
            orderStmt.setString(4, deliveryAddress);

            int orderRows = orderStmt.executeUpdate();
            if (orderRows == 0) {
                throw new SQLException("创建订单失败!");
            }

            // 获取生成的订单ID
            int orderId;
            try (ResultSet generatedKeys = orderStmt.getGeneratedKeys()) {
                if (generatedKeys.next()) {
                    orderId = generatedKeys.getInt(1);
                } else {
                    throw new SQLException("获取订单ID失败!");
                }
            }

            // 插入订单项
            String itemSql = "INSERT INTO order_items (order_id, menu_item_id, quantity, price) VALUES (?, ?, ?, ?)";
            PreparedStatement itemStmt = conn.prepareStatement(itemSql);

            for (OrderItem item : orderItems) {
                itemStmt.setInt(1, orderId);
                itemStmt.setInt(2, item.getMenuItemId());
                itemStmt.setInt(3, item.getQuantity());
                itemStmt.setDouble(4, item.getPrice());
                itemStmt.addBatch();
            }

            int[] itemRows = itemStmt.executeBatch();
            if (itemRows.length != orderItems.size()) {
                throw new SQLException("添加订单项失败!");
            }

            conn.commit(); // 提交事务
            System.out.println("下单成功! 订单ID: " + orderId + ", 总金额: ￥" + totalAmount);

        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("下单失败!");
        }
    }

    private static void viewMyOrders() {
        if (currentUser == null) {
            System.out.println("请先登录!");
            return;
        }

        System.out.println("\n===== 我的订单 =====");

        try (Connection conn = DatabaseConnection.getConnection()) {
            String sql = "SELECT o.*, r.name as restaurant_name FROM orders o " +
                    "JOIN restaurants r ON o.restaurant_id = r.id " +
                    "WHERE o.user_id = ? ORDER BY o.order_date DESC";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, currentUser.getId());
            ResultSet rs = pstmt.executeQuery();

            while (rs.next()) {
                System.out.println("订单ID: " + rs.getInt("id"));
                System.out.println("餐厅: " + rs.getString("restaurant_name"));
                System.out.println("下单时间: " + rs.getTimestamp("order_date"));
                System.out.println("总金额: ￥" + rs.getDouble("total_amount"));
                System.out.println("状态: " + rs.getString("status"));
                System.out.println("配送地址: " + rs.getString("delivery_address"));

                // 获取订单详情
                String detailSql = "SELECT mi.name, oi.quantity, oi.price " +
                        "FROM order_items oi " +
                        "JOIN menu_items mi ON oi.menu_item_id = mi.id " +
                        "WHERE oi.order_id = ?";
                PreparedStatement detailStmt = conn.prepareStatement(detailSql);
                detailStmt.setInt(1, rs.getInt("id"));
                ResultSet detailRs = detailStmt.executeQuery();

                System.out.println("订单详情:");
                while (detailRs.next()) {
                    System.out.println("   " + detailRs.getString("name") +
                            " x " + detailRs.getInt("quantity") +
                            " - ￥" + detailRs.getDouble("price"));
                }
                System.out.println();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static void updateUserInfo() {
        if (currentUser == null) {
            System.out.println("请先登录!");
            return;
        }

        System.out.println("\n===== 修改个人信息 =====");
        System.out.print("请输入新邮箱 (当前: " + currentUser.getEmail() + "): ");
        String email = scanner.nextLine();
        System.out.print("请输入新电话 (当前: " + currentUser.getPhone() + "): ");
        String phone = scanner.nextLine();
        System.out.print("请输入新地址 (当前: " + currentUser.getAddress() + "): ");
        String address = scanner.nextLine();

        try (Connection conn = DatabaseConnection.getConnection()) {
            String sql = "UPDATE users SET email = ?, phone = ?, address = ? WHERE id = ?";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, email);
            pstmt.setString(2, phone);
            pstmt.setString(3, address);
            pstmt.setInt(4, currentUser.getId());

            int rowsAffected = pstmt.executeUpdate();
            if (rowsAffected > 0) {
                currentUser.setEmail(email);
                currentUser.setPhone(phone);
                currentUser.setAddress(address);
                System.out.println("个人信息更新成功!");
            } else {
                System.out.println("个人信息更新失败!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}